﻿using Faser_Shop.Models.Database;
using Faser_Shop.Models.DTO;
using Faser_Shop.Models.RequestModel;
using Faser_Shop.Services;
using Faser_Shop.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace Faser_Shop.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class ProductController : Controller
    {

        private readonly Faser_ShopContext _db;
        private readonly IJWTService _jwtService;

        public ProductController(Faser_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 前端商品分类列表接口（列出商品分类数据）
        /// </summary>
        /// <returns>商品分类列表（分类名称、分类Id）</returns>
        [HttpGet]
        public IActionResult GetProductCategoryList()
        {
            var goodsCategoryList = _db.ProductCategories.Select(x => new
            {
                x.CategoryId,
                x.CategoryName
            }).ToList();

            return Ok(goodsCategoryList);
        }

        /// <summary>
        /// 查询商品列表接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns>商品列表（商品名称，商品Id，商品图片），总数</returns>
        [HttpGet]
        public object QueryProductList([FromQuery] QueryProductListRM model)
        {
            var query = _db.Products.AsQueryable();
            if (model.CategoryId != null)
            {
                query = query.Where(x => x.CategoryId == model.CategoryId);
            }
            if (!string.IsNullOrEmpty(model.Keyword))
            {
                query = query.Where(x => x.ProductName.Contains(model.Keyword));
            }

            var total = query.Count();
            var pageIndex = model.PageIndex;
            var pageSize = Math.Max(model.PageSize, 100);
            var productList = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(x => new Models.DTO.ProductInfo
            {
                ProductId = x.ProductId,
                ProductImage = x.ProductImage,
                ProductName = x.ProductName,
                ProductDescription = x.ProductDescription,
                ProductPrice = x.ProductPrice,
                ProductStock = x.ProductStock,

                CategoryId = x.CategoryId,
                CategoryName = x.Category.CategoryName
            }).ToList();

            return ApiResult.Success(new
            {
                total,
                productList
            });
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        /// <param name="productId"></param>
        /// <returns>商品标题，图片，价格，库存，描述</returns>
        [HttpGet]
        public object GetProductDetail(int productId)
        {
            var product = _db.Products.FirstOrDefault(x => x.ProductId == productId);
            if (product == null)
            {
                return ApiResult.PRODUCT_NOT_FOUND;
            }

            return ApiResult.Success(new Models.DTO.ProductInfo
            {
                ProductId = product.ProductId,
                ProductImage = product.ProductImage,
                ProductName = product.ProductName,
                ProductDescription = product.ProductDescription,
                ProductPrice = product.ProductPrice,
                ProductStock = product.ProductStock,

                CategoryId = product.CategoryId,
            });
        }

        /// <summary>
        /// 修改商品信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public object Update([FromBody] ProductUpdateRM model)
        {
            var product = _db.Products.FirstOrDefault(x => x.ProductId == model.ProductId);
            if(product == null)
            {
                return ApiResult.PRODUCT_NOT_FOUND;
            }
            
            if (model.Image != null)
            {
                product.ProductImage = model.Image;
            }
            if (model.Name != null)
            {
                product.ProductName = model.Name;
            }
            if(model.Price != null)
            {
                product.ProductPrice = model.Price;
            }
            if(model.ProductStock != null)
            {
                product.ProductStock = model.ProductStock;
            }

            var result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.UPDATE_FAILED_DB_NOCHANGE;
        }

    }
}
